<?php
/**
 * Created by 荣耀电竞.
 * User: 林子彦 <278805354@qq.com>
 * Date: 2018/5/17 0017
 * Time: 17:22
 */

namespace App\Admin\Repositories;

use App\Admin\Contracts\AuthRuleInterface;
use App\Admin\Models\AuthGroupAccessModel;
use App\Admin\Models\AuthGroupModel;
use App\Admin\Models\AuthRuleModel;
use App\Admin\Models\MenuModel;
use App\Base\Repositories\DbBaseRepository;
use Illuminate\Support\Facades\Request;


class DbAuthRuleRepository extends DbBaseRepository implements AuthRuleInterface
{

    //菜单权限
    private $model;

    public function __construct(AuthRuleModel $authRuleModel)
    {
        $this->model = $authRuleModel;
        $this->setModel($this->model);
    }

    public function setModel($model)
    {
        return parent::setModel($model); // TODO: Change the autogenerated stub
    }

    /**
     * 角色组模型
     * @return AuthGroupModel
     */
    public function getAuthGroupModel()
    {
        return app()->make(AuthGroupModel::class);
    }

    /**
     * 访问权限组模型
     * @return AuthGroupAccessModel
     */
    public function getAuthGroupAccessModel()
    {
        return app()->make(AuthGroupAccessModel::class);
    }

    /**
     * 菜单模型
     * @return MenuModel
     */
    public function getMeunModel()
    {
        return app()->make(MenuModel::class);
    }

    /**
     * 权限菜单权限
     * @return AuthRuleModel
     */
    public function getAuthRuleModel()
    {
        return app()->make(AuthRuleModel::class);
    }

    /**
     * 获取角色组列表
     * @param $where
     * @return \Illuminate\Database\Eloquent\Collection|mixed|static[]
     */
    public function getAuthGroupList($where)
    {

        $request=Request::instance();
        $limit=empty($request->input("limit"))?10:$request->input("limit");
        return $this->getAuthGroupModel()->newQuery()->where($where)->paginate($limit);
    }

    /**
     * 角色拥有权限
     * @param $where
     * @return mixed|void
     */
    public function getAuthGroupInfo($where)
    {
        return $this->getAuthGroupModel()->newQuery()->where($where)->first();
    }

    /**
     * 更新角色组信息
     * @param $where
     * @param $data
     * @return \App\Admin\Contracts\mixed色|int
     */
    public function updateAuthGroup($where, $data)
    {
        return $this->getAuthGroupModel()->newQuery()->where($where)->update($data);
    }

    /**
     * 删除权限组
     * @param $where
     * @return mixed|void
     */
    public function delAuthGroup($where)
    {
        $this->getAuthGroupAccessModel()->newQuery()->where("group_id", $where["id"])->delete();
        return $this->getAuthGroupModel()->newQuery()->where($where)->delete();
    }

    /**
     * 更新与创建
     * @param $data
     * @return mixed|void
     */
    public function updateOrCreateAuthGroup($data)
    {
        $id = $data["id"];
        unset($data["id"]);
        $data = $this->getAuthGroupModel()->filter($data);
        return $this->getAuthGroupModel()->newQuery()->updateOrCreate(["id" => $id], $data);
    }

    /**
     * 角色数组
     * @param $where
     * @return array|mixed
     */
    public function getAuthRuleListNameByArray($where)
    {
        return $this->getAuthRuleModel()->newQuery()->where($where)->pluck("id", "name")->toArray();
    }

    /**
     * 删除角色访问
     * @param $where
     * @return mixed
     */
    public function delUserAuthGroupAccess($where)
    {

        return $this->getAuthGroupAccessModel()->newQuery()->where($where)->delete();
    }

    /**
     * 新增用户访问
     * @param $data
     * @return $this|\Illuminate\Database\Eloquent\Model|mixed
     */
    public function saveUserAuthGroupAccess($data)
    {
        $data = $this->getAuthGroupAccessModel()->filter($data);
        return $this->getAuthGroupAccessModel()->newQuery()->create($data);
    }

    /**
     * 获取用户角色
     * @param $where
     * @return mixed|void
     */
    public function getUserAuthGroupAccessGroupId($where)
    {
        return $this->getAuthGroupAccessModel()->newQuery()->where($where)->value("group_id");
    }

    public function updateNodeByMenu()
    {

        $nodes = $this->getMeunModel()->getReturnNode(false);

        $map = array(
            'type' => array(
                'in',
                '1,2'
            )
        ); // status全部取出,以进行更新
        // 需要更新和删除的节点必然位于$rules

        $rules = $this->getAuthRuleModel()->newQuery()->where(function ($query) {
            $query->where("module", "admin");
            $query->whereIn("type", [
                1,
                2
            ]);
        })->get()->toArray();
        $data = array(); // 保存需要插入和更新的新节点
        foreach ($nodes as $value) {
            $temp['name'] = $value['url'];
            $temp['title'] = $value['title'];
            $temp['module'] = 'admin';
            if ($value['pid'] > 0) {
                $temp['type'] = $this->getAuthRuleModel()::RULE_URL;
            } else {
                $temp['type'] = $this->getAuthRuleModel()::RULE_MAIN;
            }
            $temp['status'] = 1;
            $data[strtolower($temp['name'] . $temp['module'] . $temp['type'])] = $temp; // 去除重复项
        }
        $update = array(); // 保存需要更新的节点
        $ids = array(); // 保存需要删除的节点的id

        foreach ($rules as $index => $rule) {
            $key = strtolower($rule['name'] . $rule['module'] . $rule['type']);

            if (isset($data[$key])) { // 如果数据库中的规则与配置的节点匹配,说明是需要更新的节点
                $data[$key]['id'] = $rule['id']; // 为需要更新的节点补充id值
                $update[] = $data[$key];
                unset($data[$key]);
                unset($rules[$index]);
                unset($rule['condition']);
                $diff[$rule['id']] = $rule;
            } elseif ($rule['status'] == 1) {
                $ids[] = $rule['id'];
            }
        }

        if (count($update)) {
            foreach ($update as $k => $row) {
                if ($row != $diff[$row['id']]) {
                    $this->getAuthRuleModel()->newQuery()->where("id", $row["id"])->update($row);
                }
            }
        }


        if (count($ids)) {
            $this->getAuthRuleModel()->newQuery()->whereIn("id", $ids)->update(['status' => -1]);
            // 删除规则是否需要从每个用户组的访问授权表中移除该规则?
        }
        if (count($data)) {
            //新增的数据
            $this->getAuthRuleModel()->newQuery()->insert(array_values($data));
        }
        return true;
    }

    public function getNodeMeunList()
    {
        $list = $this->getMeunModel()->newQuery()->select("id", "pid", "title as name", "url", "tip", "hide")->orderBy("sort", "asc")->get()->toArray();
        foreach ($list as $key => $value) {
            if (stripos($value['url'], MODULE_NAME) !== 0) {
                $list[$key]['url'] = MODULE_NAME . '/' . $value['url'];
            }
        }
        $nodes = list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0);
        foreach ($nodes as $key => $value) {
            if (empty($value['children'])) {
                //$nodes[$key]['child'] = $value['operator'];
                unset($nodes[$key]['children']);
            }
        }
        return $nodes;
    }


}